package com.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import java.util.Collections;

import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import com.entity.TokenEntity;
import com.utils.ValidatorUtils;
import com.utils.DeSensUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;

import com.entity.XueyuanEntity;
import com.entity.view.XueyuanView;

import com.service.XueyuanService;
import com.service.TokenService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MPUtil;
import com.utils.MapUtils;
import com.utils.CommonUtil;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 * 学员
 * 后端接口
 * @author 
 * @email 
 * @date 2024-11-23 17:52:25
 */
@RestController
@RequestMapping("/xueyuan")
public class XueyuanController {
    @Autowired
    private XueyuanService xueyuanService;




    
	@Autowired
	private TokenService tokenService;
	
	/**
	 * 登录
	 */
	@IgnoreAuth
	@RequestMapping(value = "/login")
	public R login(String username, String password, String captcha, HttpServletRequest request) {
		XueyuanEntity u = xueyuanService.selectOne(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", username));
		if(u==null || !u.getMima().equals(password)) {
			return R.error("账号或密码不正确");
		}
		
        if(!"是".equals(u.getSfsh())) return R.error("账号已锁定，请联系管理员审核。");
		String token = tokenService.generateToken(u.getId(), username,"xueyuan",  "学员" );
		return R.ok().put("token", token);
	}


	
	/**
     * 注册
     */
	@IgnoreAuth
    @RequestMapping("/register")
    public R register(@RequestBody XueyuanEntity xueyuan){
    	//ValidatorUtils.validateEntity(xueyuan);
    	XueyuanEntity u = xueyuanService.selectOne(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()));
		if(u!=null) {
			return R.error("注册用户已存在");
		}
		Long uId = new Date().getTime();
		xueyuan.setId(uId);
        xueyuanService.insert(xueyuan);
        return R.ok();
    }

	
	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}
	
	/**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
    	Long id = (Long)request.getSession().getAttribute("userId");
        XueyuanEntity u = xueyuanService.selectById(id);
        return R.ok().put("data", u);
    }
    
    /**
     * 密码重置
     */
    @IgnoreAuth
	@RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
    	XueyuanEntity u = xueyuanService.selectOne(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", username));
    	if(u==null) {
    		return R.error("账号不存在");
    	}
        u.setMima("123456");
        xueyuanService.updateById(u);
        return R.ok("密码已重置为：123456");
    }



    /**
     * 后台列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,XueyuanEntity xueyuan,
		HttpServletRequest request){
        EntityWrapper<XueyuanEntity> ew = new EntityWrapper<XueyuanEntity>();



		PageUtils page = xueyuanService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, xueyuan), params), params));
				Map<String, String> deSens = new HashMap<>();
				DeSensUtil.desensitize(page,deSens);
        return R.ok().put("data", page);
    }
    
    /**
     * 前台列表
     */
	@IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,XueyuanEntity xueyuan, 
		HttpServletRequest request){
        EntityWrapper<XueyuanEntity> ew = new EntityWrapper<XueyuanEntity>();

		PageUtils page = xueyuanService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, xueyuan), params), params));
		
				Map<String, String> deSens = new HashMap<>();
				DeSensUtil.desensitize(page,deSens);
        return R.ok().put("data", page);
    }



	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( XueyuanEntity xueyuan){
       	EntityWrapper<XueyuanEntity> ew = new EntityWrapper<XueyuanEntity>();
      	ew.allEq(MPUtil.allEQMapPre( xueyuan, "xueyuan")); 
        return R.ok().put("data", xueyuanService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(XueyuanEntity xueyuan){
        EntityWrapper< XueyuanEntity> ew = new EntityWrapper< XueyuanEntity>();
 		ew.allEq(MPUtil.allEQMapPre( xueyuan, "xueyuan")); 
		XueyuanView xueyuanView =  xueyuanService.selectView(ew);
		return R.ok("查询学员成功").put("data", xueyuanView);
    }
	
    /**
     * 后台详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        XueyuanEntity xueyuan = xueyuanService.selectById(id);
				Map<String, String> deSens = new HashMap<>();
				DeSensUtil.desensitize(xueyuan,deSens);
        return R.ok().put("data", xueyuan);
    }

    /**
     * 前台详情
     */
	@IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        XueyuanEntity xueyuan = xueyuanService.selectById(id);
				Map<String, String> deSens = new HashMap<>();
				DeSensUtil.desensitize(xueyuan,deSens);
        return R.ok().put("data", xueyuan);
    }
    



    /**
     * 后台保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody XueyuanEntity xueyuan, HttpServletRequest request){
        if(xueyuanService.selectCount(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()))>0) {
            return R.error("学员学号已存在");
        }
    	xueyuan.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(xueyuan);
    	XueyuanEntity u = xueyuanService.selectOne(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()));
		if(u!=null) {
			return R.error("用户已存在");
		}
		xueyuan.setId(new Date().getTime());
        xueyuanService.insert(xueyuan);
        return R.ok();
    }
    
    /**
     * 前台保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody XueyuanEntity xueyuan, HttpServletRequest request){
        if(xueyuanService.selectCount(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()))>0) {
            return R.error("学员学号已存在");
        }
    	xueyuan.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(xueyuan);
    	XueyuanEntity u = xueyuanService.selectOne(new EntityWrapper<XueyuanEntity>().eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()));
		if(u!=null) {
			return R.error("用户已存在");
		}
		xueyuan.setId(new Date().getTime());
        xueyuanService.insert(xueyuan);
        return R.ok().put("data",xueyuan.getId());
    }





    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody XueyuanEntity xueyuan, HttpServletRequest request){
        //ValidatorUtils.validateEntity(xueyuan);
        if(xueyuanService.selectCount(new EntityWrapper<XueyuanEntity>().ne("id", xueyuan.getId()).eq("xueyuanxuehao", xueyuan.getXueyuanxuehao()))>0) {
            return R.error("学员学号已存在");
        }
        //全部更新
        xueyuanService.updateById(xueyuan);
        // 修改token
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setUsername(xueyuan.getXueyuanxuehao());
        tokenService.update(tokenEntity, new EntityWrapper<TokenEntity>().eq("userid", xueyuan.getId()));

        return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/shBatch")
    @Transactional
    public R update(@RequestBody Long[] ids, @RequestParam String sfsh, @RequestParam String shhf){
        List<XueyuanEntity> list = new ArrayList<XueyuanEntity>();
        for(Long id : ids) {
            XueyuanEntity xueyuan = xueyuanService.selectById(id);
            xueyuan.setSfsh(sfsh);
            xueyuan.setShhf(shhf);
            list.add(xueyuan);
        }
        xueyuanService.updateBatchById(list);
        return R.ok();
    }


    

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        xueyuanService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
    
	





    @RequestMapping("/importExcel")
    public R importExcel(@RequestParam("file") MultipartFile file){
        try {
            //获取输入流
            InputStream inputStream = file.getInputStream();
            //创建读取工作簿
            Workbook workbook = WorkbookFactory.create(inputStream);
            //获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //获取总行
            int rows=sheet.getPhysicalNumberOfRows();
            if(rows>1){
                //获取单元格
                for (int i = 1; i < rows; i++) {
                    Row row = sheet.getRow(i);
                    XueyuanEntity xueyuanEntity =new XueyuanEntity();
                    xueyuanEntity.setId(new Date().getTime());
                    String xueyuanxuehao = CommonUtil.getCellValue(row.getCell(0));
                    xueyuanEntity.setXueyuanxuehao(xueyuanxuehao);
                    String mima = CommonUtil.getCellValue(row.getCell(1));
                    xueyuanEntity.setMima(mima);
                    String xueyuanxingming = CommonUtil.getCellValue(row.getCell(2));
                    xueyuanEntity.setXueyuanxingming(xueyuanxingming);
                    String xingbie = CommonUtil.getCellValue(row.getCell(3));
                    xueyuanEntity.setXingbie(xingbie);
                    String shouji = CommonUtil.getCellValue(row.getCell(4));
                    xueyuanEntity.setShouji(shouji);
                    String jifen = CommonUtil.getCellValue(row.getCell(5));
                    xueyuanEntity.setJifen(Integer.parseInt(jifen));
                    String banjimingcheng = CommonUtil.getCellValue(row.getCell(6));
                    xueyuanEntity.setBanjimingcheng(banjimingcheng);
                    String touxiang = CommonUtil.getCellValue(row.getCell(7));
                    xueyuanEntity.setTouxiang(touxiang);
                     
                    //想数据库中添加新对象
                    xueyuanService.insert(xueyuanEntity);//方法
                }
            }
            inputStream.close();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("导入成功");
    }






}
